<template>
  <div>
    <!-- 新增预定 -->
    <el-card class="card">
      <div class="header">
        <span class="line" />
        预定信息
      </div>
      <!-- form表单 -->
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="预定人姓名：" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="预定人电话：" prop="mobile">
          <el-input v-model="ruleForm.mobile" placeholder="请输入预定人电话" clearable />
        </el-form-item>
        <el-form-item label="与老人关系：" prop="relation">
          <el-select v-model="ruleForm.relation" placeholder="请选择" clearable>
            <el-option v-for="item in relationList" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="预定床位：" prop="relation">
          <el-cascader
            v-model="ruleForm.begId"
            :props="props"
            :options="getcounts"
            clearable
            @change="handleChange"
          />
        </el-form-item>
        <el-form-item label="开始日期：" prop="startDate">
          <el-date-picker
            v-model="ruleForm.startDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="预定时长（天）：" prop="day">
          <el-input v-model="ruleForm.day" placeholder="请输入预定时长" clearable />
        </el-form-item>
        <el-form-item label="定金应收：" prop="amount">
          <el-input v-model="ruleForm.amount" placeholder="请输入定金应收" clearable />
        </el-form-item>
      </el-form>
      <div class="header">
        <span class="line" />
        预定协议
      </div>
      <el-upload
        v-model:file-list="fileList"
        :headers="headers"
        class="upload-demo"
        :action="BaseUrl + '/api/upload/add'"
        multiple
      >
        <el-button type="primary">上传协议</el-button>
        <template #tip />
      </el-upload>
      <div class="btns">
        <el-button type="primary" @click="save(ruleFormRef)">保存并提交</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, defineEmits, onMounted } from "vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import type { UploadUserFile } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import { AddParams } from "../../api/market/reserve/type";
import { bedList } from "@/api/config/bed/bed";
import { buildTree } from "@/utils/treeUtil";
import { badListParams } from "@/api/config/bed/type";
import { houseList } from "@/api/config/house/house";
import { listParams } from "@/api/config/house/type";
import { buildingListData } from "@/api/config/building/type";
import { buildingList } from "@/api/config/building/building";
import { addReserve, getReserveModel, updateReserve } from "@/api/market/reserve/reserve";

//级联选择器格式转换
const props = { label: "name", value: "id" };

// 楼栋列表
const buildList = ref<buildingListData[]>([]);
const getBuildingList = async () => {
  let res = await buildingList();
  buildList.value = res.list;
  getHouseList();
};

//房间列表
const houseParams = reactive<listParams>({
  page: 1,
  pageSize: 1000,
  name: "",
  buildingId: undefined,
});
const house_list = ref<any[]>([]);
const getHouseList = async () => {
  let res = await houseList(houseParams);
  house_list.value = res.list.map((item) => ({
    id: item.id,
    name: item.name,
    pid: item.buildingId,
  }));
  getBedList();
};
//床位
const bedParams = reactive<badListParams>({
  houseId: undefined,
  page: 1,
  pageSize: 1000,
});
const bedListData = ref<any>([]);
const getBedList = async () => {
  let res = await bedList(bedParams);
  bedListData.value = res.list.map((item) => ({
    id: item.id,
    name: item.name,
    pid: item.houseId,
  }));
  mergeData([...buildList.value, ...house_list.value, ...bedListData.value]);
  // console.log("1111",bedListData.value);
};

//选择床位
const handleChange = (data: any) => {
  // console.log("7777data",data);

  if (data) {
    bedParams.houseId = data[data.length - 1];
    ruleForm.begId = data[data.length - 1];
    getBedList();
  }
};

// 合并
const getcounts = ref([]);
const mergeData = (data: any) => {
  getcounts.value = buildTree(data);
  // console.log("getCounts999",getcounts.value);
};

//表单绑定
const ruleFormRef = ref<FormInstance>();

//添加老人信息
const ruleForm = reactive<AddParams>({
  elderlyId: 0,
  name: "",
  mobile: "",
  relation: "",
  begId: 0,
  startDate: "",
  day: null,
  amount: null,
  files: [],
});

const router = useRouter();
const route = useRoute();
if (route.query.oldId) {
  //老人id
  ruleForm.elderlyId = Number(route.query.oldId);
}

//根路径
const BaseUrl = import.meta.env.VITE_APP_API_URL;
// 图片根路径
const imgUrl = ref(import.meta.env.VITE_IMG_URL);
const headers = { Authorization: localStorage.getItem("token") };

const emit = defineEmits(["close"]);

//关系
const relationList = reactive(["父子关系", "父女关系", "母子关系", "母女关系", "其他"]);

//规则
const rules = reactive<FormRules<AddParams>>({
  name: [{ required: true, message: "请输入预定人姓名", trigger: "blur" }],
  mobile: [{ required: true, message: "请输入预定人电话", trigger: "blur" }],
  relation: [
    {
      required: true,
      message: "请选择与老人关系",
      trigger: "change",
    },
  ],
  begId: [
    {
      required: true,
      message: "请选择预定床位",
      trigger: "change",
    },
  ],
  startDate: [
    {
      required: true,
      message: "请选择开始时间",
      trigger: "change",
    },
  ],
  day: [{ required: true, message: "请输入预定时长", trigger: "blur" }],
  amount: [{ required: true, message: "请输入定金应收", trigger: "blur" }],
});

//取消
const cancel = () => {
  router.push("/market/reserve");
};

//图片
let fileList = ref<UploadUserFile[]>([]);

//保存
const save = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let imgs = fileList.value.map((item: any) =>
        item.response ? item.response.data.url : item.name
      );
      ruleForm.files = imgs.map((item) => ({ file: item }));

      if (route.params.id) {
        //修改
        await updateReserve(ruleForm);
        ElMessage({
          message: "修改成功",
          type: "success",
        });
      } else {
        //添加
        await addReserve(ruleForm);
        ElMessage({
          message: "添加成功",
          type: "success",
        });
      }
      //跳转预定登记
      router.push("/market/reserve");
    } else {
      ElMessage({
        message: "error submit!",
        type: "warning",
      });
    }
  });
};

//预定登记详情
const getDetail = async (id: number) => {
  let res = await getReserveModel(id);
  Object.assign(ruleForm, res);

  let arr = res.files.map((item) => ({ name: item.file }));

  fileList.value = arr as any;
};

onMounted(() => {
  getBuildingList();
  if (route.params.id) {
    //详情
    getDetail(Number(route.params.id));
  }
});
</script>

<style scoped>
.card {
  width: 98%;
  margin: 0 auto;
  margin-top: 10px;

  .header {
    display: flex;
    align-items: center;
    height: 50px;

    .line {
      display: block;
      width: 6px;
      height: 20px;
      margin-right: 8px;
      background-color: #529bfd;
    }
  }

  .demo-ruleForm {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    width: 80%;

    .el-form-item {
      width: 480px;
    }
  }

  .btns {
    margin: 50px 0;
    text-align: center;
  }
}
</style>
